<?php
/**
 * created by zzy
 * date: 2017/10/24 9:28
 */

namespace App\Api\Service\Category\Controllers;

use App\Eloquent\Ygt\Category;
use App\Eloquent\Ygt\CategoryFields;
use App\Eloquent\Ygt\DepartmentUser;
use Framework\BaseClass\Api\Controller;
use App\Engine\Func;

class IndexController extends Controller
{
    public $userId      = 25;
    //分类列表,已二级联动形式返
    public function all()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $type               = request('type',2);//1成品(没有什么用),2材料,2018-7-7
        if(!$userId || !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['company_id'=>$companyId];
        $collection         = Category::getList($where);
        $groupList          = $collection->groupBy('pid')->toArray();
        switch($type)
        {
            case 1:
                //成品(没有什么用) 2018-7-7
                $parentPid  = 1;
                break;
            case 2:
                $parentPid  = 2;
                break;
            default:
        }
        $parentList         = isset($groupList[$parentPid]) ? $groupList[$parentPid] : [];
        $result             = [];
        foreach($parentList as $key=>$val)
        {
            $valId          = $val['id'];
            if(isset($groupList[$valId]))
            {
                $sonData        = $groupList[$valId];
                $tempData       = [];
                foreach($sonData as $k=>$v)
                {
                    $tempData[]   = [
                        'id'=>$v['id'],
                        'title'=>$v['cat_name'],
                    ];
                }
                $temp           = [
                    'id'=>$valId,
                    'title'=>$val['cat_name'],
                    'data'=>$tempData
                ];
                $result[]       = $temp;
            }
        }
        return $result;
    }
    //添加分类或者编辑分类
    public function add()
    {
        $userId         = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo       = DepartmentUser::getCurrentInfo($userId);
        if(!$userId || !$userInfo )
        {
            xThrow( ERR_PARAMETER,'登录过期' );
        }
        $companyId      = $userInfo->company_id;
        //过滤必填信息
        $params         = request()->all();
        $mustArr        = [
            'pid'=>'上级分类不能为空',
            'cat_name'=>'名称不能为空',
        ];
        foreach($mustArr as $key=>$val)
        {
            if(!isset($params[$key]) || empty($params[$key]))
            {
                xThrow( ERR_PARAMETER,$val );
            }
        }
        //$isEdit==true是编辑,false是添加
        $id                 = request('id',0);
        $pid                = request('pid',0);
        $isEdit             = $id===0 ? false : true;
        $tableData          = [
            'pid'=>$pid,
            'cat_name'=>$params['cat_name'],
            'img_id'=>$params['img_id'],
            'company_id'=>$companyId,
            'unit'=>$params['unit']
        ];

        //限制相同名称分类提交
        if($pid == 2){//一级分类
            $tmpWhere = [];
            $tmpWhere[] = ['pid','=',$pid];
            $tmpWhere[] = ['id','!=',$id];
            $tmpWhere[] = ['cat_name','=',$params['cat_name']];
            $tmpWhere[] = ['company_id','=',$companyId];

            $tmpCount = \App\Eloquent\Ygt\Category::where($tmpWhere)->get()->count();
            if($tmpCount){
                return [
                    'code' => 1,
                    'message' => '分类名称已存在',
                ];
            }
        }else{
            $tmpWhere = [];
            $tmpWhere[] = ['pid','!=',2];
            $tmpWhere[] = ['id','!=',$id];
            $tmpWhere[] = ['cat_name','=',$params['cat_name']];
            $tmpWhere[] = ['company_id','=',$companyId];

            $tmpCount = \App\Eloquent\Ygt\Category::where($tmpWhere)->get()->count();
            if($tmpCount){
                return [
                    'code' => 1,
                    'message' => '分类名称已存在',
                ];
            }
        }


        if($isEdit){
            //编辑分类
            $categroyId         = $id;
            $where              = ['id'=>$categroyId];
            $updateResult       = Category::updateOneData($where,$tableData);
            $editResult         = $updateResult===false ? false :true;
            $messageArr         = ['error'=>'编辑失败','success'=>'编辑成功'];
        }else{
            //过滤分类的属性
            $categoryFieldsJson = request('cate_fields_arr','');
            $categoryFieldsArr  = json_decode(htmlspecialchars_decode($categoryFieldsJson), true);
            if($categoryFieldsArr)
            {
//                foreach($categoryFieldsArr as $key=>$val)
//                {
//                    $valFieldName   = $val['field_name'];
//                    if(empty($valFieldName))
//                    {
//                        xThrow( ERR_PARAMETER,'字段名称必填' );
//                        break;
//                    }
//                }
            }
            //添加分类
            $insertResult       = Category::insertOneData($tableData,'id');
            $categroyId         = $insertResult;
            $editResult         = $insertResult>0 ? true : false;
            //$pid==1或2时,不是一级分类,--------------0.0------------
            //只有在添加分类的时候才能添加自定义的属性
            if($insertResult>0 && $categoryFieldsArr)
            {
                //添加分类的属性
                $tableDataList      = [];
                foreach($categoryFieldsArr as $key=>$val)
                {
                    $temp               = [
                        'category_id'=>$categroyId,
                        'field_name'=>$val['field_name'],
                        'field_unit'=>$val['unit'],
                        'is_must'=>$val['is_must'],
                        'type'=>$val['type'],
                        'is_compute'=> isset($val['is_compute']) ? $val['is_compute'] : 0,
                    ];
                    $tableDataList[]    = $temp;
                }
                \DB::table('ygt_category_fields')->insert($tableDataList);
            }
            $messageArr         = ['error'=>'添加失败','success'=>'添加成功'];
        }
        if(!$editResult)
        {
            xThrow(ERR_UNKNOWN,$messageArr['error']);
        }
        $result             = ['message'=>$messageArr['success']];
        return $result;
    }

}



















